<script setup>
import { useRoute } from "vue-router";
import { computed, onMounted, onUnmounted, ref } from "vue";
import { ElMessageBox, ElNotification } from "element-plus";
import {
  getDisinfectStatusById,
  controlUpperModel,
} from "@/api/disinfect/robot-manage";
import { getDisinfectFaultSnapshot } from "@/api/disinfect/log-center";
import { disinfectTask } from "@/api/disinfect/task-manage.js";
import useKonva from "@/composables/useKonva";
import MapDialog from "./MapDialog.vue";

const { loading, initStage, initImage, showRobot } = useKonva();

const route = useRoute();

// 电池相关信息
const batteryInfo = [
  { label: "电压", prop: "batteryVoltage" },
  { label: "电流", prop: "batteryCurrent" },
  { label: "功率", prop: "batteryPower" },
  { label: "电池温度", prop: "batteryTemperature" },
  { label: "电池类型", prop: "batteryType" },
  { label: "电池状态", prop: "batteryStatus" },
];

// 运动相关信息
const runningSpeedInfo = [
  { label: "X速度", prop: "speedX" },
  { label: "Y速度", prop: "speedY" },
  { label: "Z速度", prop: "speedZ" },
];

// 获取机器人详情数据
let timer;
const details = ref({
  robotDisinfectTask: {},
  robotDisinfectMap: {},
});
getDetails();
async function getDetails() {
  if (route.query.id) {
    clearTimeout(timer);
    const { data } = await getDisinfectStatusById(route.query.id);
    details.value = data;
    timer = setTimeout(() => getDetails(), 5000);
  }
  if (route.query.logId) {
    const { data } = await getDisinfectFaultSnapshot(route.query.logId);
    details.value = data;
  }
  await initImage(details.value.robotDisinfectMap.url);
  showRobot(details.value.coordinateY / 0.05, details.value.coordinateX / 0.05);
}

// 格式化程序
const formatter = {
  nav(val) {
    return val === 0 || val === 1 ? "故障" : "正常";
  },
  wheel(val) {
    return val !== 1 ? "故障" : "正常";
  },
  uvc(val) {
    return val === -1 ? "故障" : "正常";
  },
  spray(val) {
    return val === -1 ? "故障" : "正常";
  },
  charge(val) {
    return val === 1 ? "充电中" : "未充电";
  },
  task(val) {
    if (val === "start") return "执行中";
    if (val === "pause") return "已暂停";
    if (val === "continues") return "执行中";
    if (val === "cancel") return "已取消";
    if (val === "end") return "已结束";
    if (val === "download") return "待下载";
    return "未知";
  },
};

// 设备控制表单
const formData = ref({
  device: "close",
  fog: 0,
  protect: false,
});

// 设备控制下发
async function onSubmit() {
  await ElMessageBox.confirm("确认继续操作吗", "警告");
  const { message } = await controlUpperModel({
    code: route.query.id,
    ...formData.value,
  });
  ElNotification({ title: "提示", type: "success", message });
}

const taskStatus = computed(() => {
  if (!details.value.robotDisinfectTask) return;
  return formatter.task(details.value.robotDisinfectTask.status);
});
// 任务控制
async function taskControl(status) {
  await ElMessageBox.confirm("确认继续操作吗", "警告");
  const { message } = await disinfectTask.control({
    id: details.value.robotDisinfectTask.id,
    status,
  });
  ElNotification({ title: "提示", type: "success", message });
}

const position = ref();

const mapDialogVisible = ref(false);
const contorlStatus = ref("");
function openMapDialog(status) {
  contorlStatus.value = status;
  mapDialogVisible.value = true;
}

onMounted(() => {
  initStage(
    "position",
    position.value.offsetWidth,
    position.value.offsetHeight
  );
});

onUnmounted(() => {
  clearTimeout(timer);
});
</script>

<template>
  <div class="h-main p-6 grid grid-cols-12 grid-rows-5 gap-6">
    <div
      class="flex rounded-md shadow-md bg-[#f1f3fa] select-none px-4 col-span-full"
    >
      <img class="m-6 block" src="@/assets/images/disinfect/robot.png" />
      <div class="flex flex-col justify-between grow my-8">
        <div class="text-2xl font-bold" data-test="details-name">
          {{ details.name }}
        </div>
        <div
          class="flex items-center text-lg text-[#acb5d9]"
          data-test="robot-status"
        >
          <div class="mr-4">{{ taskStatus }}</div>
          <template v-if="route.query.id && taskStatus">
            <el-button @click="taskControl('pause')">暂停</el-button>
            <el-button @click="taskControl('continues')">继续</el-button>
            <el-button @click="taskControl('cancel')">取消</el-button>
          </template>
        </div>
      </div>
      <div
        :class="details.abnormalState === 1 ? 'bg-[#f83c20]' : 'bg-[#50d4b4]'"
        data-test="details-abnormalState"
        class="flex items-center justify-center text-white aspect-square rounded-full text-2xl font-bold m-6"
      >
        {{ details.abnormalState === 1 ? "异常" : "正常" }}
      </div>
    </div>
    <div
      class="col-span-3 row-span-2 border border-solid border-[#ddd] p-8 rounded-md shadow-md overflow-hidden"
    >
      <h3>状态</h3>
      <el-form
        data-test="robot-statu"
        label-width="100px"
        label-position="left"
        label-suffix="："
      >
        <el-form-item label="导航">
          {{ formatter.nav(details.navStatus) }}
        </el-form-item>
        <el-form-item label="运动系统">
          {{ formatter.wheel(details.wheelStatus) }}
        </el-form-item>
        <el-form-item label="紫外线">
          {{ formatter.uvc(details.uvlight) }}
        </el-form-item>
        <el-form-item label="雾化器">
          {{ formatter.spray(details.atomizer) }}
        </el-form-item>
      </el-form>
    </div>
    <div
      class="col-span-9 row-span-2 border border-solid border-[#ddd] p-8 rounded-md shadow-md flex justify-around overflow-hidden"
    >
      <div>
        <h3>电池</h3>
        <el-progress
          type="circle"
          :percentage="details.battery"
          :stroke-width="20"
          :width="160"
          color="#32E3D4"
        >
          <template #default="{ percentage }">
            <div class="text-sm mb-1">电量</div>
            <div>{{ percentage }} %</div>
          </template>
        </el-progress>
      </div>
      <div>
        <el-form label-width="100px" label-position="left" label-suffix="：">
          <el-form-item
            v-for="item in batteryInfo"
            :key="item.prop"
            :label="item.label"
          >
            {{ details[item.prop] }}
          </el-form-item>
        </el-form>
      </div>
      <div>
        <h3>液量</h3>
        <el-progress
          type="circle"
          :percentage="details.liquid"
          :stroke-width="20"
          :width="160"
          color="#3F80F2"
        >
          <template #default="{ percentage }">
            <div class="text-sm mb-1">液量</div>
            <div>{{ percentage }} %</div>
          </template>
        </el-progress>
      </div>
    </div>
    <div
      class="col-span-4 row-span-2 border border-solid border-[#ddd] p-8 rounded-md shadow-md"
    >
      <div v-loading="loading" class="flex flex-col h-full">
        <h3>位置坐标</h3>
        <div id="position" ref="position" class="h-full"></div>
      </div>
    </div>
    <div
      class="col-span-4 row-span-2 border border-solid border-[#ddd] p-8 rounded-md shadow-md"
    >
      <h3>无线充电</h3>
      <el-form label-width="100px" label-position="left" label-suffix="：">
        <el-form-item label="充电状态">
          {{ formatter.charge(details.chargeStatus) }}
        </el-form-item>
      </el-form>
      <h3 class="!mt-6">运行速度</h3>
      <el-form label-width="100px" label-position="left" label-suffix="：">
        <el-form-item
          v-for="item in runningSpeedInfo"
          :key="item.prop"
          :label="item.label"
        >
          {{ details[item.prop] }}
        </el-form-item>
      </el-form>
    </div>
    <div
      v-loading="route.query.logId"
      data-test="robot-control"
      :element-loading-svg="`<path />`"
      class="col-span-4 row-span-2 border border-solid border-[#ddd] p-8 rounded-md shadow-md"
    >
      <h3>设备控制</h3>
      <el-form
        :model="formData"
        label-width="100px"
        label-position="left"
        label-suffix="："
      >
        <el-form-item label="设备状态" prop="device">
          <el-select v-model="formData.device">
            <el-option label="关闭所有设备" value="close" />
            <el-option label="开启紫外线" value="uvc" />
            <el-option label="开启雾化器" value="spray" />
            <el-option label="开启紫外线和雾化器" value="all" />
          </el-select>
        </el-form-item>
        <el-form-item label="雾量" prop="fog">
          <el-slider v-model="formData.fog" class="mx-2" />
        </el-form-item>
        <el-form-item label="人体保护" prop="protect">
          <div class="w-full flex justify-between">
            <el-switch v-model="formData.protect" />
            <el-button type="primary" @click="onSubmit">提交</el-button>
          </div>
        </el-form-item>
      </el-form>
      <h3 class="!mt-6">机器人控制</h3>
      <el-button @click="openMapDialog('navigate')">导航下发</el-button>
      <el-button @click="openMapDialog('calibration')">位置校准</el-button>
      <MapDialog
        v-model:visible="mapDialogVisible"
        :code="route.query.id"
        :status="contorlStatus"
      ></MapDialog>
    </div>
  </div>
</template>

<style scoped>
h3 {
  margin-top: 0;
}
.el-form-item {
  margin-bottom: 0;
}
</style>
